﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Seagull.Configuration;

namespace Seagull.Controls
{
    public partial class ChannelSelector : UserControl
    {
        private string[] _channelNames =
            // 这是设计时的默认值
            Enumerable.Range(1, 16).Select(i => "通道" + i).ToArray();

        public static string GetChannelName(byte channelId)
        {
            return Config.Instance.ChannelConfig[channelId].Name;
        }

        public ChannelSelector()
        {
            InitializeComponent();
            _channelList.ItemCheck += OnChannelListItemCheck;
        }

        public IEnumerable<byte> SelectedChannels
        {
            get { return _channelList.CheckedIndices.Cast<int>().Select(GetChannelId); }
        }

        public string[] ChannelNames
        {
            get { return _channelNames; }
            set
            {
                _channelNames = value;
                _channelList.Items.Clear();
                _channelList.Items.AddRange(_channelNames);
            }
        }

        public void LoadChannelNamesFromConfig()
        {
            ChannelNames = Config.Instance.ChannelConfig.ChannelNumbers
                .Select(i => GetChannelName((byte)i))
                .ToArray();
        }

        public event EventHandler<ChannelSelectionChangedEventArgs> ChannelSelectionChanged;

        protected virtual void OnChannelSelectionChanged(object sender, ChannelSelectionChangedEventArgs e)
        {
            var handler = ChannelSelectionChanged;
            if(handler != null)
                handler(sender, e);
        }

        private void OnChannelListItemCheck(object sender, ItemCheckEventArgs e)
        {
            // 最多选择x项
            if(_channelList.CheckedItems.Count >= Config.Instance.UIConfig.MaxChannelSelection
                && e.NewValue == CheckState.Checked)
            {
                e.NewValue = CheckState.Unchecked;
            }
            else
            {
                BeginInvoke((Action)(() =>
                    OnChannelSelectionChanged(this, new ChannelSelectionChangedEventArgs
                    {
                        Channel = GetChannelId(e.Index),
                        IsAdded = e.NewValue == CheckState.Checked,
                    })));
            }
        }

        private static byte GetChannelId(int checkedChannel)
        {
            return (byte)(checkedChannel + 1);
        }

    }

    public class ChannelSelectionChangedEventArgs : EventArgs
    {
        public byte Channel { get; set; }

        public bool IsAdded { get; set; }
    }
}
